package com.lcxsoft.paymentservice.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.lcxsoft.commonutils.JwtUtils;
import com.lcxsoft.commonutils.R;
import com.lcxsoft.feign.clients.UserClient;
import com.lcxsoft.paymentservice.entity.Payment;
import com.lcxsoft.paymentservice.mapper.PaymentMapper;
import com.lcxsoft.paymentservice.query.PaymentQuery;
import com.lcxsoft.paymentservice.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lcx
 * @since 2022-01-25
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    private String APP_ID = "2021000118688269";
    private String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDY1PjXQebdhNcw4XRGk9Sv5UnPRwOMOeXrsEvwb+aiuVPqRopN58LMuSR7z8RBnMSbUk/rfZpbAOaKmQxZ287yUFt7YHpt0/zAH6j/B+mdJlGiaQoeEa7ZkfsXdsn7B/0O78y8Zm52evVK6T8Z29HOKvQ64PZ0VFrPzyOCvJwBNiVYdqjBmlYpSbZfOyx/8WviIroz7ukAsjhIbSV7YOoeJLzvZxvhC03weM3eYZulN0t9MOzAZmQ38r9z5EvxJiOOSGBxfnGAVubT4QdH+AAToTF0ysMM1ErY6TxkjozyjPF0RFzXotPc136zW0XE0u5mTbdL6Gmi1GRO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Rq9PmS/rFRnhL/4NHfbGDP6wTZK7HxfLIWRbYYgH9IY5CZ7rcbhfs/rQaLvgUEVIBCTCL8YZlNVe3asw6/ZMA8G7GzzKlx2rvTOYM/UwQZD5WFfVarsgzk/+imH7wyIWhEsEZ6YKv/ad7OeYk0nlr8V8q2m";
    private String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqZhlRKqWNEB5U5wuGSYwI58Q+BvoNhra9tGQUHu4nXLsw89oUWp/G4R/2mUhnHfDpvkXOZKcJGuTw7tDg1UmMpR5sPVNaexHTGdlv8fnRnQSHSGlk/OOcjZ0U4PEvMRTAuJQdRDVOMqLEdfXX99dy9vUgGTj3t8+evkwkeZomXSl96Hbs9soUWTbhZ//pFjhiHovtxC5EwKphiwZg170X1e1KDqRrdkjKDLuZesJ1nHUw+oN1ev9BiXwNnIlo16FKPqtWmX2lvJJvl3nq/B5tGOy6N+DVG2Q+NahrFrRrZzSLfs18DJtW/to6uvVHxy5QTT3xW//+PKReYlNysS5XwIDAQAB";
    private String CHARSET = "utf-8";
    private String SERVER_URL = "https://openapi.alipaydev.com/gateway.do";

    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private UserClient userClient;



    @Override
    public void pay(PaymentQuery query, HttpServletRequest requestService, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(SERVER_URL, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //异步通知接口
        request.setNotifyUrl("http://szswpt.vicp.cc:57393/foodbox/paymentservice/paymentUrl/payNotify");
        //支付完成返回接口
        //request.setReturnUrl("");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", UUID.randomUUID().toString().toUpperCase().substring(20));
        bizContent.put("total_amount", query.getTotalAmount().doubleValue());
        bizContent.put("subject", query.getToken());
        bizContent.put("product_code", "QUICK_WAP_WAY");
        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        String form = alipayClient.pageExecute(request).getBody();
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @Override
    public R payNotify(HttpServletRequest request) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)
        //订单总额
        BigDecimal total_amount = new BigDecimal(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"));
        //商品名称
        String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                Payment payment = new Payment();
                payment.setPaymentId(out_trade_no);
                payment.setUserId(subject);
                payment.setPaymentName("充值");
                payment.setTotalAmount(total_amount);
                payment.setTradeStatus("支付成功");
                payment.setCreatetime(LocalDateTime.now());
                paymentMapper.insert(payment);

                userClient.updateUserInfo(total_amount, subject);

                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                return R.ok().message("交易成功");
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            //out.clear();
            //out.println("success");	//请不要修改或删除
        }else{//验证失败
            return R.ok().message("验证失败");
        }
        return R.ok().message("交易失败");
    }

}
